In this article, we will learn to add interactivity to our applications to make them engaging and dynamic. The browser is an event-driven application. Everything that a user does in the browser fires an event, from clicking buttons to even just moving the mouse. In plain JavaScript, we can listen to these events and attach a JavaScript function to interact with them. But in React, however, we don't have to interact with the browser's event loop in raw JavaScript as React provides a way for us to handle events using props. React provides a lot of props we can set to listen for different browser events, such as click, touch, drag, scroll, selection events, and many more. We will now become familiar with a few proptypes like onClick.
We have a search symbol in our activity list header but no search box, so we'll build an interaction that displays a search component when the user clicks on it. We will make changes to the header element by sending a dynamic className parameter to the input element.
When the user clicks on the search incon element, we'll want to call a method that updates the component's state, which will update the searchInputClasses object. It is rather easy to use the onClick handler. Let's make this component stateful (it needs to know if the search field is visible or not). We can make our component stateful by utilizing the constructor() function:
When the user clicks on the button, we want to change the state to indicate that the searchVisible flag has been modified. To allow the user to close/hide the field after a second click on the search symbol, we will toggle the state instead of just setting it to true.Let's create this method to bind our click event:
Let's include an if statement to update the searchInputClasses if this.state.SearchVisible is true.
Finally, we can attach a click handler (using the onClick prop) on the icon element to call our new showSearch() method.
In the next article we will use onSubmit and onChange props to update our search box to capture the text inside the search field and search for the required activity, The whole code for this post is easily available on my GitHub .
« Read Previous Article in this Series Read Next Article in this Series »